﻿/*
 * 文件名称：
 * 程序员：wangyun
 * 创建时间：2008/05/27
 * 
 * 功能说明：功能模块添加或修改页面
 * 
 * 修改人员：
 * 
 * 修改日期：
 * 
 * 修改记录：
 */

using System;
using System.Web;
using System.IO;
using System.Data;
using System.Web.UI.WebControls;
using Whir.Common.WebHelper;
using System.Xml;

public partial class Whir_System_Module_Contents_Model : System.Web.UI.Page
{
    protected string Action;
    protected int ModelID;
    protected string url;

    protected void Page_Load(object sender, EventArgs e)
    {
        RoleHelper.IsLogin();    //登录判断

        Action = NetRequest.GetQueryString("Action");
        ModelID = NetRequest.GetQueryInt("ModelID");
        url = Server.UrlDecode(NetRequest.GetQueryString("url"));

        if (!IsPostBack)
        {
            this.txtSysTableName.Attributes.Add("style", "ime-mode:disabled;");
            this.txtTableName.Attributes.Add("style", "ime-mode:disabled;");
        }
    }

    /// <summary>
    /// 绑定需修改的功能模块
    /// </summary>
    /// <param name="modelID">功能模块 ID</param>
    private void BindModel(int modelID)
    {
        Whir.Model.Whir_Model model = new Whir.Model.Whir_Model();
        Whir.BLL.Whir_Model bll = new Whir.BLL.Whir_Model();
        model = bll.GetModel(modelID);
        if (model != null)
        {
            ddlModuleMark.SelectedValue = model.moduleMark;
            txtModelName.Text = model.modelName;
            txtModelDesc.Text = model.modelDesc;
            lblTablePrefix.Text = model.tableName;
        }
    }

    /// <summary>
    /// 选择系统功能模块
    /// </summary>
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (RadioButton1.Checked)
        {
            if (!string.IsNullOrEmpty(rblModelTemplate.SelectedValue))
            {
                string templateName = rblModelTemplate.SelectedItem.Text + ".xml";

                string modelMark = hfSysModule.Value;
                string modelName = txtSysModelName.Text.Trim();
                string modelDesc = txtSysModelDesc.Text.Trim();
                string modelIcon = "";
                bool isUse = true;

                string tableName = ContentManage.GetCustomTableName(txtSysTableName.Text.Trim());

                //验证该表名是否存在于数据库中
                if (new Whir.Common.SqlDMOHelper().IsExistTable(tableName))
                {
                    JsHelper.Alert(Page, "功能模块添加失败，可能该表名已存在！");
                    return;
                }
                ModelTemplateHelper.Import(templateName, modelMark, modelName, modelDesc, modelIcon, tableName, isUse);
                JsHelper.redirect(Page, "功能模块信息添加成功！", "ModelManage.aspx");
            }
            else
            {
                JsHelper.Alert(Page, "请选择一个系统功能模块，再执行“添加操作”！");
            }
        }
    }

    /// <summary>
    /// 选择自定义功能模块
    /// </summary>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Whir.Model.Whir_Model model = new Whir.Model.Whir_Model();
        Whir.BLL.Whir_Model bll = new Whir.BLL.Whir_Model();

        if (RadioButton2.Checked)
        {
            string modelMark = ddlModuleMark.SelectedItem.Value;
            string modelName = txtModelName.Text.Trim();
            string modelDesc = txtModelDesc.Text.Trim();
            string modelIcon = "";
            bool isUse = true;
            bool isShowColumn = true;
            bool isGroup = false;

            string tableName = ContentManage.GetCustomTableName(txtTableName.Text);

            //验证该表名是否存在于数据库中
            if (new Whir.Common.SqlDMOHelper().IsExistTable(tableName))
            {
                JsHelper.Alert(Page, "功能模块添加失败，可能该表名已存在！");
                return;
            }
            bool flag = false;

            //创建功能模块对应的表
            Whir.Common.SqlDMOHelper dmo = new Whir.Common.SqlDMOHelper();

            //返回创建表的成功与否
            flag = dmo.CreateTable(tableName);

            if (flag)
            {
                model.moduleMark = modelMark;
                model.modelName = modelName;
                model.modelDesc = modelDesc;
                model.modelIcon = modelIcon;
                model.tableName = tableName;
                model.isUse = isUse;
                model.IsShowColumn = isShowColumn;
                model.IsGroup = isGroup;
                //添加功能模块
                int modelId = bll.Add(model);

                //创建默认字段（TypeID, CreateDate, IsPublish）
                CreateDefaultColumn(modelId, "TypeID", "栏目编号", FieldType.None, tableName);
                CreateDefaultColumn(modelId, "IsCheck", "审核", FieldType.BoolType, tableName);
                CreateDefaultColumn(modelId, "CreateUser", "创建人", FieldType.TextType, tableName);
                CreateDefaultColumn(modelId, "CreateDate", "发布日期", FieldType.DateTimeType, tableName);

                JsHelper.redirect(Page, "功能模块信息添加成功！", "ModelManage.aspx");
            }
            else
            {
                JsHelper.Alert(Page, "功能模块添加失败，可能该表名已存在！");
            }
        }
    }

    /// <summary>
    /// 绑定功能模块标识
    /// </summary>
    private void BindModuleMark()
    {
        ddlModuleMark.DataSource = new Whir.BLL.Whir_Module().GetList();
        ddlModuleMark.DataTextField = "moduleName";
        ddlModuleMark.DataValueField = "moduleMark";
        ddlModuleMark.DataBind();
    }

    /// <summary>
    /// 绑定系统模板
    /// </summary>
    private void BindSysModelTemplate()
    {
        string templateName = "";
        rblModelTemplate.Items.Clear();
        foreach (DataRow row in ModelTemplateHelper.GetModelTemplates().Rows)
        {
            templateName = row["name"].ToString();
            if (!templateName.Contains("-"))
            {
                rblModelTemplate.Items.Add(new ListItem(Path.GetFileNameWithoutExtension(templateName), templateName));
            }
        }
    }

    /// <summary>
    /// 绑定自创模板
    /// </summary>
    private void BindMyModelTemplate()
    {
        string templateName = "";
        rblMyModelTemplate.Items.Clear();
        foreach (DataRow row in ModelTemplateHelper.GetModelTemplates().Rows)
        {
            templateName = row["name"].ToString();
            if (templateName.Contains("-"))
            {
                rblMyModelTemplate.Items.Add(new ListItem(Path.GetFileNameWithoutExtension(templateName), templateName));
            }
        }
        if (rblMyModelTemplate.Items.Count <= 0)
        {
            JsHelper.Alert(Page, "经查询，暂无导出的记录！现跳转到“自定义功能模块”选项");
            RadioButton3.Checked = false;
            tbMy.Visible = false;
            RadioButton2.Checked = true;
            tbcreate.Visible = true;

            //绑定功能模块标识
            BindModuleMark();
        }
    }

    #region 设置默认字段
    /// <summary>
    /// 创建默认字段（TypeID, CreateDate, IsPublish）
    /// </summary>
    /// <returns>状态</returns>
    private bool CreateDefaultColumn(int modelId, string fieldName, string alias, FieldType fieldType, string tableName)
    {
        bool flag = false;
        int fieldID;

        #region 创建字段
        Whir.Model.Whir_Field fieldModel = new Whir.Model.Whir_Field();
        Whir.BLL.Whir_Field fieldBll = new Whir.BLL.Whir_Field();

        fieldModel.modelID = modelId;
        fieldModel.fieldName = fieldName;
        fieldModel.alias = alias;
        fieldModel.rating = false;
        fieldModel.fieldTip = "";
        fieldModel.fieldDesc = "";
        fieldModel.isRequired = true;
        fieldModel.isUse = true;
        fieldModel.sort = 0;
        fieldModel.banUserIDs = "";
        fieldModel.banRoleIDs = "";
        fieldModel.isValidate = true;
        fieldModel.validateType = 0;
        fieldModel.validateMsg = "";
        fieldModel.validateTo = "";
        fieldModel.createUserID = 0;
        fieldModel.updateUserID = 0;
        fieldModel.fieldType = (int)fieldType;
        fieldModel.typeName = FieldCommon.GetFieldType(fieldType)["typeName"].ToString();
        fieldModel.typeLength = Convert.ToInt32(FieldCommon.GetFieldType(fieldType)["typeLength"]);
        fieldModel.isAllowNull = Convert.ToBoolean(FieldCommon.GetFieldType(fieldType)["isAllowNull"]);
        fieldModel.isIdentity = Convert.ToBoolean(FieldCommon.GetFieldType(fieldType)["isIdentity"]);
        fieldModel.identityIncrement = Convert.ToInt32(FieldCommon.GetFieldType(fieldType)["identityIncrement"]);
        fieldModel.identitySeed = Convert.ToInt32(FieldCommon.GetFieldType(fieldType)["identitySeed"]);
        fieldModel.defaultValue = FieldCommon.GetFieldType(fieldType)["defaultValue"].ToString();
        fieldID = fieldBll.Add(fieldModel);
        #endregion

        #region 添加字段类型
        switch (fieldType)
        {
            case FieldType.BoolType:
                Whir.BLL.Whir_FieldOption fieldOptionBLL = new Whir.BLL.Whir_FieldOption();
                Whir.Model.Whir_FieldOption fieldOptionModel = new Whir.Model.Whir_FieldOption();
                fieldOptionModel.fieldID = fieldID;
                fieldOptionModel.optionType = 2;    //1、下拉列表框2、单选按钮组3、多选按钮组
                fieldOptionModel.bindValue = "是|否";
                fieldOptionModel.cellNum = 0;
                fieldOptionModel.defaultValue = "是";
                fieldOptionModel.bindType = 1;
                fieldOptionModel.sql = "";
                fieldOptionModel.sqlChild = "";
                fieldOptionModel.height = "";
                fieldOptionModel.width = "";
                fieldOptionModel.firthOption = "";
                fieldOptionModel.onChange = "";
                fieldOptionModel.valueField = "";
                fieldOptionModel.textField = "";
                fieldOptionBLL.Add(fieldOptionModel);
                break;
            case FieldType.DateTimeType:
                Whir.BLL.Whir_FieldDateText fieldDateTextBLL = new Whir.BLL.Whir_FieldDateText();
                Whir.Model.Whir_FieldDateText fieldDateTextModel = new Whir.Model.Whir_FieldDateText();
                fieldDateTextModel.fieldID = fieldID;
                fieldDateTextModel.dateFormat = 1;
                fieldDateTextModel.defaultValue = "1";
                fieldDateTextModel.width = "200";
                fieldDateTextBLL.Add(fieldDateTextModel);
                break;
            case FieldType.None:
                Whir.BLL.Whir_FieldText fieldTextBll = new Whir.BLL.Whir_FieldText();
                Whir.Model.Whir_FieldText fieldTextModel = new Whir.Model.Whir_FieldText();
                fieldTextModel.fieldID = fieldID;
                fieldTextModel.textWidth = "";
                fieldTextModel.textHeight = "";
                fieldTextModel.textType = 1;
                fieldTextModel.defaultValue = "@TypeID";
                fieldTextBll.Add(fieldTextModel);
                break;
            case FieldType.TextType:
                Whir.BLL.Whir_FieldText fieldTextBll1 = new Whir.BLL.Whir_FieldText();
                Whir.Model.Whir_FieldText fieldTextModel1 = new Whir.Model.Whir_FieldText();
                fieldTextModel1.fieldID = fieldID;
                fieldTextModel1.textWidth = "";
                fieldTextModel1.textHeight = "";
                fieldTextModel1.textType = 1;
                fieldTextModel1.defaultValue = "@@adminTrueName";
                fieldTextBll1.Add(fieldTextModel1);
                break;
        }
        #endregion

        #region 添加字段到数据库表中
        Whir.Common.SqlDMOHelper dmo = new Whir.Common.SqlDMOHelper();
        SQLDMO.Column Col1 = new SQLDMO.Column();
        Col1.Name = fieldModel.fieldName;
        Col1.Datatype = fieldModel.typeName;
        Col1.Length = fieldModel.typeLength;
        Col1.AllowNulls = fieldModel.isAllowNull;
        Col1.Default = fieldModel.defaultValue;
        flag = dmo.AddColumnInTable(tableName, Col1);
        #endregion
        return flag;
    }
    #endregion


    protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
    {
        tbsys.Visible = true;
        tbMy.Visible = false;
        tbcreate.Visible = false;
        //绑定已有的模板
        BindSysModelTemplate();
    }

    protected void RadioButton3_CheckedChanged(object sender, EventArgs e)
    {
        tbsys.Visible = false;
        tbMy.Visible = true;
        tbcreate.Visible = false;
        //绑定已有的模板
        BindMyModelTemplate();
    }

    protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
    {
        tbsys.Visible = false;
        tbMy.Visible = false;
        tbcreate.Visible = true;

        //绑定功能模块标识
        BindModuleMark();
    }

    protected void rblModelTemplate_SelectedIndexChanged(object sender, EventArgs e)
    {
        string templateName = rblModelTemplate.SelectedItem.Value;
        string filePath = ModelTemplateHelper.GetModelTemplatePath();
        XmlTextReader r = new XmlTextReader(filePath + templateName);

        if (templateName != "0")
        {
            while (r.Read())
            {
                if (r.NodeType == XmlNodeType.Element && r.Name == "ModelMark")
                {
                    r.Read();
                    hfSysModule.Value = r.Value;
                    continue;
                }
                if (r.NodeType == XmlNodeType.Element && r.Name == "ModelName")
                {
                    r.Read();
                    txtSysModelName.Text = r.Value;
                    continue;
                }
                if (r.NodeType == XmlNodeType.Element && r.Name == "ModelDesc")
                {
                    r.Read();
                    txtSysModelDesc.Text = r.Value;
                    continue;
                }
            }
        }
    }

    protected void Button4_Click(object sender, EventArgs e)
    {
        if (RadioButton3.Checked)
        {
            if (!string.IsNullOrEmpty(rblMyModelTemplate.SelectedValue))
            {
                string templateName = rblMyModelTemplate.SelectedItem.Text + ".xml";

                string modelMark = hfMyModule.Value;
                string modelName = txtMyModelName.Text.Trim();
                string modelDesc = txtMyModelDesc.Text.Trim();
                string modelIcon = "";
                bool isUse = true;

                string tableName = ContentManage.GetCustomTableName(txtMyTableName.Text.Trim());

                //验证该表名是否存在于数据库中
                if (new Whir.Common.SqlDMOHelper().IsExistTable(tableName))
                {
                    JsHelper.Alert(Page, "功能模块添加失败，可能该表名已存在！");
                    return;
                }
                ModelTemplateHelper.Import(templateName, modelMark, modelName, modelDesc, modelIcon, tableName, isUse);
                JsHelper.redirect(Page, "功能模块信息添加成功！", "ModelManage.aspx");
            }
            else
            {
                JsHelper.Alert(Page, "请选择一个已导出的功能模块，再执行“添加操作”！");
            }
        }
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        Response.Redirect("ModelManage.aspx");
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("ModelManage.aspx");
    }
    protected void Button5_Click(object sender, EventArgs e)
    {
        Response.Redirect("ModelManage.aspx");
    }

    protected void rblMyModelTemplate_SelectedIndexChanged(object sender, EventArgs e)
    {
        string templateName = rblMyModelTemplate.SelectedItem.Value;
        string filePath = ModelTemplateHelper.GetModelTemplatePath();
        XmlTextReader r = new XmlTextReader(filePath + templateName);

        if (templateName != "0")
        {
            while (r.Read())
            {
                if (r.NodeType == XmlNodeType.Element && r.Name == "ModelMark")
                {
                    r.Read();
                    hfMyModule.Value = r.Value;
                    continue;
                }
                if (r.NodeType == XmlNodeType.Element && r.Name == "ModelName")
                {
                    r.Read();
                    txtMyModelName.Text = r.Value;
                    continue;
                }
                if (r.NodeType == XmlNodeType.Element && r.Name == "ModelDesc")
                {
                    r.Read();
                    txtMyModelDesc.Text = r.Value;
                    continue;
                }
            }
        }
    }
}